use super::response::{ModulesInfoRes, ModulesList};
use crate::model::db;
use crate::model::request::{ModulesEdit, ModulesEditDetail, ModulesInfo, ModulesSearch};
use sqlx::{self};

use super::task;

// 创建 modules
pub async fn create_modules(data: ModulesInfo) -> Result<(), sqlx::Error> {
    let pool = db::get_pool().expect("Failed to get database pool");

    // 插入 modules
    let module_id = sqlx::query("INSERT INTO tb_modules (name, modules_img, remark, created_at, updated_at) VALUES (?, ?, ?, NOW(), NOW())")
        .bind(data.name)
        .bind(data.modules_img)
        .bind(data.remark)
        .execute(pool).await?;

    // 插入 Task 数据，并关联到 tb_modules
    for task in data.task_list {
        task::add_task(module_id.last_insert_id(), task).await?;
    }

    Ok(())
}

// 修改
pub async fn edit_modules(data: ModulesEdit) -> Result<(), sqlx::Error> {
    let pool = db::get_pool().expect("Failed to get database pool");

    // === 修改 modules ===
    let modules_data = data.modules_detail;
    let sql_query = "UPDATE tb_modules SET name = ?, modules_img = ?, remark = ?,updated_at = NOW() WHERE id = ?";
    let _modules_res = sqlx::query(sql_query)
        .bind(modules_data.name)
        .bind(modules_data.modules_img)
        .bind(modules_data.remark)
        .bind(modules_data.id)
        .execute(pool)
        .await?;

    // === task add ===
    let task_add = data.task_add.unwrap();
    for task in task_add {
        task::add_task(modules_data.id.unwrap(), task).await?;
    }

    // === task edit ===
    let edit_task = data.task_edit.unwrap();
    for task in edit_task {
        task::edit_task(task).await?;
    }

    // === task delete ===
    let delete_task = data.task_delete.unwrap();
    for task in delete_task {
        task::delete_task(task).await?;
    }

    Ok(())
}

// 获取 modules list
pub async fn get_modules_list(data: &ModulesSearch) -> Result<ModulesList, sqlx::Error> {
    let pool = db::get_pool().unwrap();
    let offset = (data.page - 1) * data.page_size;

    // 第一步：构建最基础的查询
    let mut query =
        "SELECT id,name,modules_img,remark,created_at,updated_at FROM tb_modules".to_string();

    // 构建搜索条件
    let mut conditions = Vec::new();

    if let Some(id) = &data.id {
        conditions.push(format!("id = '{}'", id));
    }

    if let Some(name) = &data.name {
        conditions.push(format!("name LIKE '%{}%'", name));
    }

    // 添加搜索条件到查询语句
    if !conditions.is_empty() {
        query.push_str(" WHERE ");
        query.push_str(&conditions.join(" AND "));
    }

    // 添加排序和分页限制
    query.push_str(" ORDER BY created_at DESC LIMIT ? OFFSET ?");

    println!("sql: {}", query);
    // 执行查询
    let topic_list = sqlx::query_as::<_, ModulesInfoRes>(&query)
        .bind(data.page_size)
        .bind(offset)
        .fetch_all(pool)
        .await?;

    // 获取总条数
    let count_query = format!(
        "SELECT COUNT(*) as total FROM tb_modules {}",
        if !conditions.is_empty() {
            format!("WHERE {}", conditions.join(" AND "))
        } else {
            "".to_string()
        }
    );
    let count_result: (Option<i64>,) = sqlx::query_as(count_query.as_str()).fetch_one(pool).await?;
    let count = count_result.0.unwrap_or(0); // 空结果处理

    let res = ModulesList {
        list: topic_list,
        total: count,
    };

    Ok(res)
}

// 获取详情
pub async fn get_modules_detail(id: u64) -> Result<ModulesInfoRes, sqlx::Error> {
    let pool = db::get_pool().unwrap();
    let res = sqlx::query_as::<_, ModulesInfoRes>("SELECT * FROM tb_modules WHERE id=?")
        .bind(id)
        .fetch_one(pool)
        .await;
    match res {
        Ok(i) => Ok(i),
        Err(e) => Err(e),
    }
}
